package com.example.test.activity;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.test.R;
import com.example.test.R.drawable;
import com.example.test.R.id;
import com.example.test.R.layout;
import com.example.test.dao.DataBaseHelper;
import com.example.test.model.Constants;
import com.example.test.model.FormatTools;
import com.example.test.model.social_api.NetAPI;
import com.example.test.model.social_api.SinaAPI;
import com.netease.microblog.oauth2.Oauth2;
import com.netease.microblog.oauth2.OauthExchangeActivity;
import com.renn.rennsdk.AccessToken;
import com.renn.rennsdk.RennClient;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.exception.WeiboException;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.tencent.weibo.sdk.android.api.util.Util;
import com.tencent.weibo.sdk.android.component.Authorize;
import com.tencent.weibo.sdk.android.component.sso.AuthHelper;
import com.tencent.weibo.sdk.android.component.sso.OnAuthListener;
import com.tencent.weibo.sdk.android.component.sso.WeiboToken;
import com.tencent.weibo.sdk.android.model.GlobalVar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView.ScaleType;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.Toast;



public class BindAccountActivity extends Activity {
	
	private static final String[] choices={"新浪微博","腾讯微博","人人网","网易微博","搜狐微博","QQ空间"};
	private static final String[] codeChoise={"sina","QQ","renn","netease","sohu","qzone"};
	private Spinner spWeibos;
	private Button btAuth;
	private int ichoice = 0;
	private ArrayAdapter<String> adapter;
	public void listAuthedAccount()
	{
		LinearLayout layout=(LinearLayout)findViewById(R.id.llAuthed1);
		layout.removeAllViews();
		final String [] arrFieldName ={"sina_token","qq_token","renn_token","net_token","sohu_token"};
		int [] arrLogoId={R.drawable.ic_com_sina_weibo_sdk_logo,R.drawable.qq_bigicon,R.drawable.renren_bigicon,R.drawable.net_bigicon,R.drawable.sohu_bigicon};
		SQLiteDatabase database=DataBaseHelper.getRedDatabase(getApplicationContext());
		Cursor cursor=  database.query("account",arrFieldName, "name=? ", new String[]{GlobalVar.userName}, null, null, null);
	    if(cursor.getCount()>0)
	    {
	    	cursor.moveToFirst();
	    	int j=0;
	    	
	    	LinearLayout row = null;
	    	final int arr[]=new int[1];
	    	for(int i=0;i<5;i++)
	    	{
	    		
	    		if(cursor.getString(i)!=null&&!cursor.getString(i).trim().equals(""))
	    		{
	    			if(j%2==0)
	    			{
	    				row=new LinearLayout(getApplicationContext());
	    				android.widget.LinearLayout.LayoutParams params=new android.widget.LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
	    				row.setOrientation(LinearLayout.HORIZONTAL);
	    				row.setLayoutParams(params);
                        layout.addView(row);
	    			}
	    			ImageView view =new ImageView(getApplicationContext());
	    			
	    			LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(150,150);
	    			params.weight=1.0f;
	    			view.setLayoutParams(params);
	    			view.setImageBitmap( Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), arrLogoId[i]), 200, 200, true));
    				final int k=i;
	    			view.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View arg0) {
							AlertDialog.Builder builder = new AlertDialog.Builder(BindAccountActivity.this);
						    //设置标题
						    builder.setTitle("notice");
						    //设置提示内容
						    builder.setMessage("你确认要注销该账户么?");
						    builder.setNegativeButton("取消", null);
						    //设置确定按钮
						    builder.setPositiveButton("确定", new  DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface arg0, int arg1) {
									DataBaseHelper helper = new DataBaseHelper(BindAccountActivity.this, "data", null, 2);
									SQLiteDatabase database = helper.getWritableDatabase();
									database.execSQL("update account set "+arrFieldName[k]+" ='' where name ='"+GlobalVar.userName+"';");
									Toast.makeText(getApplicationContext(), "注销成功", 1000).show();
									helper.close();
									if(codeChoise[arr[0]].equals(GlobalVar.enWhich))
									{
										GlobalVar.enWhich="all";
									}
									BindAccountActivity.this.listAuthedAccount();
								}
							});
						    AlertDialog dlg=builder.create();
						    dlg.show();
						
						}
					});
	    			row.addView(view);
	    			j++;
	    		}
	    	}
	    	if(j%2==1)
	    	{
	    		ImageView view =new ImageView(getApplicationContext());
    			
    			LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(150,150);
    			params.weight=1.0f;
    			view.setLayoutParams(params);
    			
	    		row.addView(view);
	    	}
	    }
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		LinearLayout layout=(LinearLayout)findViewById(R.id.llAuthed);
		listAuthedAccount();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_addaccount);
		listAuthedAccount();
		spWeibos = (Spinner) findViewById(R.id.spWeibos);
		btAuth=(Button) findViewById(R.id.btAuth);
		//将可选内容与ArrayAdapter连接起来
		adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,choices);
		
		//设置下拉列表的风格
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		//将adapter 添加到spinner中
		spWeibos.setAdapter(adapter);
		
		//添加事件Spinner事件监听  
		spWeibos.setOnItemSelectedListener(new SpinnerSelectedListener());
		
		//设置默认值
		spWeibos.setVisibility(View.VISIBLE);
		
		btAuth.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				switch(ichoice)
				{
				case 0: SinaAuth(); break;
				case 1: QQAuth();break;
				case 2: RennAuth();break;
				case 3: NetAuth();break;
				case 4: SohuAuth();break; 
				case 5: txAuth();break;
				}
				
			}
			private void txAuth()
			{
				Tencent tencent = Tencent.createInstance(Constants.TXAPP_KEY, BindAccountActivity.this.getApplicationContext());
			    if(!tencent.isSessionValid())
			    {
			    	tencent.login(BindAccountActivity.this, "all", new IUiListener() {
						
						@Override
						public void onError(UiError arg0) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void onComplete(Object arg0) {
							try {
								
								Toast.makeText(BindAccountActivity.this, ((JSONObject)arg0).getString("access_token"), 1000).show();
								BindAccountActivity.this.listAuthedAccount();
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						
						@Override
						public void onCancel() {
							// TODO Auto-generated method stub
							
						}
					});
			    }
			}
			
			
			private void SinaAuth()
			{
				WeiboAuth auth=new WeiboAuth(BindAccountActivity.this, Constants.APP_KEY,Constants.REDIRECT_URL,Constants.SCOPE);
				auth.anthorize(new SinaWeiboAuthListener (BindAccountActivity.this));
			}
			private void NetAuth()
			{
				Oauth2.getInstance().setClientId(Oauth2.getInstance().getConsumerKey());
				Oauth2.getInstance().setRedirectUri("http://www.baidu.com");
				Oauth2.getInstance().setResponseType("code");
				Oauth2.getInstance().setDisplay("mobile");
				Log.v("netease",
						Oauth2.getInstance().getAuthorizationRequestUrl());
				OauthExchangeActivity dialog = new OauthExchangeActivity(BindAccountActivity.this,
						Oauth2.getInstance().getAuthorizationRequestUrl());
				dialog.setOnDismissListener(new OnDismissListener() {
					@Override
					public void onDismiss(DialogInterface dialog) {
						if(com.netease.microblog.util.Util.isStringEmpty(Oauth2.getInstance().getAccessToken()))
							Toast.makeText(BindAccountActivity.this, "未授权成功", 1000).show();
						else{
							
							Toast.makeText(BindAccountActivity.this, "授权成功", 1000).show();
							DataBaseHelper helper = new DataBaseHelper(BindAccountActivity.this, "data", null, 2);
							SQLiteDatabase database = helper.getWritableDatabase();
							database.execSQL("update account set net_token ='"+Oauth2.getInstance().getAccessToken()+"' where name ='"+GlobalVar.userName+"';");
							helper.close();
							NetAPI.getUserInfo("", null, new Handler(){

								@Override
								public void handleMessage(Message msg) {
									final List<HashMap<String, String>> lArrHashData=(List<HashMap<String, String>>) msg.obj;
									if(lArrHashData!=null)
									{
										DataBaseHelper helper = new DataBaseHelper(BindAccountActivity.this, "data", null, 2);
										SQLiteDatabase database = helper.getWritableDatabase();
										database.execSQL("update account set net_uid ='"+lArrHashData.get(0).get("id")+"' where name ='"+GlobalVar.userName+"';");
										helper.close();
									}
									super.handleMessage(msg);
								}});
							BindAccountActivity.this.listAuthedAccount();
							
						}
					}
				});
				dialog.show();
			}
			private void SohuAuth()
			{
				com.sohu.microblog.oauth2.Oauth2.getInstance().setClientId(Oauth2.getInstance().getConsumerKey());
				com.sohu.microblog.oauth2.Oauth2.getInstance().setRedirectUri("http://www.baidu.com");
				com.sohu.microblog.oauth2.Oauth2.getInstance().setResponseType("code");
				com.sohu.microblog.oauth2.Oauth2.getInstance().setDisplay("mobile");
				Log.v("netease",
						Oauth2.getInstance().getAuthorizationRequestUrl());
				com.sohu.microblog.oauth2.OauthExchangeActivity dialog = new com.sohu.microblog.oauth2.OauthExchangeActivity(BindAccountActivity.this,
						"https://api.t.sohu.com/oauth2/authorize?client_id=clSvUmEGM7mVOatNWwgW&display=mobile&redirect_uri=http://www.baidu.com&response_type=token&scope=basic");
				dialog.setOnDismissListener(new OnDismissListener() {
					@Override
					public void onDismiss(DialogInterface dialog) {
						if(com.sohu.microblog.util.Util.isStringEmpty(com.sohu.microblog.oauth2.Oauth2.getInstance().getAccessToken()))
							Toast.makeText(BindAccountActivity.this, "未授权成功", 1000).show();
						else{
							
							Toast.makeText(BindAccountActivity.this, "授权成功", 1000).show();
							DataBaseHelper helper = new DataBaseHelper(BindAccountActivity.this, "data", null, 2);
							SQLiteDatabase database = helper.getWritableDatabase();
							database.execSQL("update account set sohu_token ='"+com.sohu.microblog.oauth2.Oauth2.getInstance().getAccessToken()+"' where name ='"+GlobalVar.userName+"';");
							helper.close();
							BindAccountActivity.this.listAuthedAccount();
							
						}
					}
				});
				dialog.show();
			}
			private void RennAuth()
			{
				final RennClient rennClient = RennClient.getInstance(BindAccountActivity.this); //获取实例
				rennClient.init("265274", "02c19c5423bd47cb8803dfedafa2b7ae", "7d35459724a34c338f631d697f9ab424");//设置应用程序信息
				
				rennClient
				.setScope("read_user_blog read_user_photo read_user_feed read_user_status read_user_album "
						+ "read_user_comment read_user_share publish_blog publish_share "
						+ "send_notification photo_upload status_update create_album "
						+ "publish_comment publish_feed");
				rennClient.setLoginListener(new RennClient.LoginListener() {
					
					@Override
					public void onLoginSuccess() {
						
						Log.v("renn", rennClient.getAccessToken().accessToken);
						
						DataBaseHelper helper = new DataBaseHelper(BindAccountActivity.this, "data", null, 2);
						SQLiteDatabase database = helper.getWritableDatabase();
						database.execSQL("update account set renn_token ='"+rennClient.getAccessToken().accessToken+"' where name ='"+GlobalVar.userName+"';");
						helper.close();
						BindAccountActivity.this.listAuthedAccount();
					}
					
					@Override
					public void onLoginCanceled() {
						// TODO Auto-generated method stub
						
					}
				});
				rennClient.login(BindAccountActivity.this);
			}
			
			private void QQAuth()
			{
				long appid = Long.valueOf(Util.getConfig().getProperty("APP_KEY"));
				String app_secket = Util.getConfig().getProperty("APP_KEY_SEC");
				auth(appid, app_secket);
			}
			

			private void auth ( long appid,String app_secket ) {
				final Context context = BindAccountActivity.this.getApplicationContext();
				//注册当前应用的appid和appkeysec，并指定一个OnAuthListener
				//OnAuthListener在授权过程中实施监听
				AuthHelper.register(BindAccountActivity.this, appid, app_secket, new QQWeiboAuthListener(BindAccountActivity.this));
				AuthHelper.auth(BindAccountActivity.this, "");
			}
			
		});
		
		
		
		
	}
	
	//使用数组形式操作
	class SpinnerSelectedListener implements OnItemSelectedListener{


		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			ichoice=arg2;
			
		}

		public void onNothingSelected(AdapterView<?> arg0) {
		}
		
		
	}
}

//腾讯授权监听器
class QQWeiboAuthListener implements OnAuthListener
{
	Context This;
	public QQWeiboAuthListener(Context This)
	{
		super();
		this.This=This;
	}
	//如果当前设备没有安装腾讯微博客户端，走这里
	@Override
	public void onWeiBoNotInstalled() {
		Toast.makeText(This, "QQWeiBoNotInstalled", 1000)
				.show();
		AuthHelper.unregister(This);
		Intent i = new Intent(This,Authorize.class);
		This.startActivity(i);
	}

	//如果当前设备没安装指定版本的微博客户端，走这里
	@Override
	public void onWeiboVersionMisMatch() {
		Toast.makeText(This, "onWeiboVersionMisMatch",
				1000).show();
		AuthHelper.unregister(This);
		Intent i = new Intent(This,Authorize.class);
		This.startActivity(i);
	}

	//如果授权失败，走这里
	@Override
	public void onAuthFail(int result, String err) {
		Toast.makeText(This, "result : " + result, 1000)
				.show();
		AuthHelper.unregister(This);
	}

	//授权成功，走这里
	//授权成功后，所有的授权信息是存放在WeiboToken对象里面的，可以根据具体的使用场景，将授权信息存放到自己期望的位置，
	//在这里，存放到了applicationcontext中
	@Override
	public void onAuthPassed(String name, WeiboToken token) {
		
		Toast.makeText(This, "passed", 1000).show();
		GlobalVar.QQToken=token.accessToken;
		DataBaseHelper helper = new DataBaseHelper(This, "data", null, 2);
		SQLiteDatabase database = helper.getWritableDatabase();
		database.execSQL("update account set qq_token ='"+GlobalVar.QQToken+"' , qq_uid = '"+token.openID+"' where name ='"+GlobalVar.userName+"';");
		helper.close();
		((BindAccountActivity)This).listAuthedAccount();
		Util.saveSharePersistent(This, "ACCESS_TOKEN", token.accessToken);
		Util.saveSharePersistent(This, "EXPIRES_IN", String.valueOf(token.expiresIn));
		Util.saveSharePersistent(This, "OPEN_ID", token.openID);
//		Util.saveSharePersistent(context, "OPEN_KEY", token.omasKey);
		Util.saveSharePersistent(This, "REFRESH_TOKEN", "");
//		Util.saveSharePersistent(context, "NAME", name);
//		Util.saveSharePersistent(context, "NICK", name);
		Util.saveSharePersistent(This, "CLIENT_ID", Util.getConfig().getProperty("APP_KEY"));
		Util.saveSharePersistent(This, "AUTHORIZETIME",
				String.valueOf(System.currentTimeMillis() / 1000l));
		AuthHelper.unregister(This);
	}
}


//新浪授权监听器
class SinaWeiboAuthListener implements WeiboAuthListener
{

	private Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			GlobalVar.sinaUid=(String)msg.obj;
			DataBaseHelper helper = new DataBaseHelper(This, "data", null, 2);
			SQLiteDatabase database = helper.getWritableDatabase();
			database.execSQL("update account set sina_uid ='"+msg.obj +"' where name ='"+GlobalVar.userName+"';");
			helper.close();
			((BindAccountActivity)This).finish();
			super.handleMessage(msg);
		}
		
	};
	Context This;
	public SinaWeiboAuthListener(Context This)
	{
		this.This=This;
	}
	@Override
	public void onComplete(Bundle arg0) {
		
		GlobalVar.sinaAccessToken =Oauth2AccessToken.parseAccessToken(arg0);
		SinaAPI.getUserUid(handler);
		DataBaseHelper helper = new DataBaseHelper(This, "data", null, 2);
		SQLiteDatabase database = helper.getWritableDatabase();
		database.execSQL("update account set sina_token ='"+Oauth2AccessToken.parseAccessToken(arg0).getToken()+"' where name ='"+GlobalVar.userName+"';");
		helper.close();
		((BindAccountActivity)This).listAuthedAccount();
	}

	@Override
	public void onCancel() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onWeiboException(WeiboException arg0) {
		// TODO Auto-generated method stub
		
	}
	
}
